import { ActionReducerMapBuilder, createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
import { Department } from '@/type/DepartmentType';
import { fetchDepartmentListAPI } from '@/API/departmentAPI';


type InitialState = {
  departmentList: Department[],
}

const initialState = {
  departmentList: [],
};

/**
 * @description 获取科室列表的异步函数
 * */
export const fetchDepartmentList = createAsyncThunk('fetchDepartmentList', async (_, { rejectWithValue }) => {
  try {
    const { data } = await fetchDepartmentListAPI();
    return data;
  } catch (error: any) {
    return rejectWithValue(error.message);
  }
});

const departmentStore = createSlice({
  name: 'departmentStore',
  initialState,
  reducers: {},
  extraReducers(builder: ActionReducerMapBuilder<InitialState>) {
    builder.addCase(fetchDepartmentList.fulfilled, (state: InitialState, action: PayloadAction<Department[]>) => {
      const { payload } = action;
      state.departmentList = payload;
    });
  },
});


export default departmentStore.reducer;